package com.asseco.mio.codex.controllers;

import com.asseco.mio.codex.AssMark;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import org.appfuse.Constants;

@Controller
@RequestMapping("/assMarkform*")
public class AssMarkFormController extends BaseFormController {

    private GenericManager<AssMark, String> assMarkManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setAssMarkManager(@Qualifier("assMarkManager") GenericManager<AssMark, String> assMarkManager) {
        this.assMarkManager = assMarkManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    public AssMarkFormController() {
        setCancelView("redirect:assmarks");
        setSuccessView("redirect:assmarks");
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected AssMark showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String userString = request.getRemoteUser();
        try {
            if (!request.isUserInRole(Constants.ADMIN_ROLE)) {
                throw new Exception("");
            }

        } catch (Exception e) {

            response.sendRedirect("/MIO/mainMenu");
        }
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assmarkform", "assmark.show", assMarkManager.get(id).getName(),
                    "", request.getRemoteHost(), new Date()));
            return assMarkManager.get(id);
        }

        return new AssMark();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(AssMark assMarks, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }
        if (validator != null) { // validator is null during testing
            validator.validate(assMarks, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "assMarkform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (assMarks.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assmarkform", "assmark.delete", assMarks.getName(),
                    "", request.getRemoteHost(), new Date()));
            assMarkManager.remove(assMarks.getId());
            saveMessage(request, getText("assMark.deleted", locale));


        } else {
            assMarkManager.save(assMarks);
            String key = (isNew) ? "assMark.added" : "assMark.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assmarkform", key, assMarks.getName(),
                    "", request.getRemoteHost(), new Date()));

            if (!isNew) {
                success = "redirect:assMarkform?id=" + assMarks.getId();
            }
        }

        return success;
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }
}
